<?php

namespace App\Admin\Forms;


use App\Models\Posts\WxPost;
use App\Models\WxCircle;
use App\Models\WxNotice;
use App\Models\WxShopOrder;
use App\Models\WxShopOrderGoods;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;


class OrderGoodsForms extends Form implements LazyRenderable
{
    use LazyWidget;


    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $id = $input['id'];
        $state = $input['state'];

        $updated_at = date('Y-m-d H:i:s', time());
        WxShopOrderGoods::where('id', $id)->update([
            'state' => $state,
            'updated_at' => $updated_at
        ]);

        $oginfo = WxShopOrderGoods::where('id', $id)->first();
        $user_id = WxShopOrder::where('id', $oginfo['order_id'])->value('user_id');

        $ogCount = WxShopOrderGoods::where('order_id', $oginfo['order_id'])->count();
        $ogtCount = WxShopOrderGoods::where('order_id', $oginfo['order_id'])->where('state', 3)->count();

        if ($ogCount == $ogtCount) {
            WxShopOrder::where('id', $oginfo['order_id'])->update([
                'pay_status' => 3,
                'status' => 4,
                'updated_at' => $updated_at
            ]);
        }

        $nr = '您购买的：' . $oginfo['name'] . '【' . $oginfo['product'] . '】×' . $oginfo['quantity'] . '件' . ' 的售后申请已处理，退款金额会在24小时内原路返回，请注意查收；有任何问题请及时联系在线客服为您处理。';

        // 发送通知
        (new WxNotice())->addNotice($user_id, '商品售后通知', $nr, 0);

        return $this->response()
            ->success('处理成功')
            ->refresh();
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $this->hidden('id')->value($this->payload["id"]);

        $this->text('state', "状态")
            ->help('0正常，1退款中，2退货退款，3已退款；修改为【3已退款】会自动发送通知提现用户。');
    }

}
